package com.gmail.avereshchaga.web.transport;

import com.gmail.avereshchaga.db.entity.IItem;
import com.gmail.avereshchaga.db.entity.ItemImpl;
import com.gmail.avereshchaga.db.service.IItemService;
import com.gmail.avereshchaga.db.service.IUserSessionIdService;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Class performs the functions of the controller operations entity Item
 *
 * @author <a href="mailto:avereshchaga@gmail.com">Vereshchaga Alexey</a>
 */
@Controller
public class ItemTransport {

    @Autowired
    private IItemService itemService;
    @Autowired
    private IUserSessionIdService userSessionIdService;

    /**
     * Calls methods to save a list of items
     *
     * @param sessionId id defines the ability to perform the method
     * @param items items to save
     */
    @RequestMapping(value = "saveItem")
    @ResponseBody
    public void saveItem(@RequestParam("sessionId") String sessionId,
            @RequestParam("items") String items) {
        if (userSessionIdService.findBySessionId(sessionId)) {
            List<IItem> itemsList = new ArrayList();
            ObjectMapper mapper = new ObjectMapper();
            try {
                itemsList = mapper.readValue(items, new TypeReference<ArrayList<ItemImpl>>() {
                });
            } catch (JsonParseException ex) {
                Logger.getLogger(ItemTransport.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JsonMappingException ex) {
                Logger.getLogger(ItemTransport.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ItemTransport.class.getName()).log(Level.SEVERE, null, ex);
            }
            for (IItem item : itemsList) {
                if (item.getName().equals("Deleted")) {
                    itemService.deleteItem(item.getId());
                } else {
                    item.setCreatedAt(new Date());
                    item.setUser(userSessionIdService.findUserBySessionId(sessionId).getUser());
                    itemService.updateItem(item);
                }
            }
        }
    }

    /**
     * Call method of search all items
     *
     * @param sessionId id defines the ability to perform the method
     * @param pageStr current page of the list
     * @return list of Items
     */
    @RequestMapping(value = "itemsAll")
    @ResponseBody
    public List findAll(@RequestParam("sessionId") String sessionId, @RequestParam("page") String pageStr) {
        List items = new ArrayList();
        String itemsStr = null;
        if (userSessionIdService.findBySessionId(sessionId)) {
            Integer page = Integer.parseInt(pageStr);
            items = itemService.findAll(page);
        }
        return items;
    }

    /**
     * Call method of search by filter
     *
     * @param sessionId id defines the ability to perform the method
     * @param code code of item
     * @param name name of item
     * @param createDate date when item was created
     * @param username name of the user who created the item
     * @param pageStr current page of the list
     * @return list of Items found by filter
     */
    @RequestMapping(value = "itemsByFilter")
    @ResponseBody
    public List findByFilter(@RequestParam("sessionId") String sessionId,
            @RequestParam("code") String code,
            @RequestParam("name") String name,
            @RequestParam("createDate") String createDate,
            @RequestParam("username") String username,
            @RequestParam("page") String pageStr) {

        List items = new ArrayList();
        if (userSessionIdService.findBySessionId(sessionId)) {
            Date date = null;
            Integer page = Integer.parseInt(pageStr);
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
            if (!createDate.equals("")) {
                try {
                    date = dateFormat.parse(createDate);
                } catch (ParseException ex) {
                    Logger.getLogger(InvoiceTransport.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            items = itemService.findByFilter(code, name, date, username, page);
        }
        return items;
    }
}
